package com.mall.malladminbackend.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mall.malladminbackend.dto.LoginDto;
import com.mall.malladminbackend.entity.SysUser;
import com.mall.malladminbackend.mapper.SysUserMapper;
import com.mall.malladminbackend.model.R;
import com.mall.malladminbackend.utils.JwtUtils;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Set;

@Service
@AllArgsConstructor
public class SysUserService {

    private SysUserMapper sysUserMapper;
    private PasswordEncoder passwordEncoder;
    private JwtUtils jwtUtils;


    public R checkUsernameAndPassword(LoginDto loginDto) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("name", loginDto.getUsername());

        SysUser sysUser = sysUserMapper.selectOne(qw);

        if(null != sysUser && passwordEncoder.matches(loginDto.getPassword(), sysUser.getPassword())) {
            /**
             * 用户登录成功需要查询用户的权限
              SELECT DISTINCT sm.perms
                 FROM sys_user su
              	    JOIN sys_user_role sur ON su.id = sur.user_id
              			JOIN sys_role sr ON sr.id = sur.role_id
              			JOIN sys_role_menu srm ON srm.role_id = sr.id
              			JOIN sys_menu sm ON sm.id = srm.menu_id
              			WHERE su.name = 'lux' AND sm.type IN (1, 2) AND sm.perms IS NOT NULL AND sm.perms != ''
             */
//            List<String> authorizes = Lists.newArrayList("sys:user:view", "sys:user:add");
            Set<String> authorizes = sysUserMapper.getPermsOfUser(loginDto.getUsername());
            if(!CollectionUtils.isEmpty(authorizes)) {  // 用户有权限
                return R.buildSuccess(jwtUtils.generateJwt(sysUser.getName(), authorizes));
            }else {
                return R.buildFailure("没有任何权限");
            }
        }else {
            return R.buildFailure("用户名或者密码错误.");
        }
    }
}
